from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
import json,os
from web.settings import BASE_DIR
# from  .. viewsindex import uploads


from myadmin import models
from django.contrib.auth.hashers import make_password, check_password
# Create your views here.

# 前台首页
def index(request):
    '''
    存储格式
    ['name':'点心','zilei':['name':'糕点','goodslist':[goodsobject,goodsobject]]]
    
    '''
    # 获取所有的一级分类
    data = models.Cates.objects.filter(pid=0)
    # print(data)
    # 再获取一级分类下的二级分类
    for i in data:
        i.zilei = models.Cates.objects.filter(pid=i.id)
    context = {'data':data}

    return render(request,'home/index.html',context)



# 订单确认
def orderconfirm(request):
    try:
        # 接收购物车商品id cartid
        cartids = request.GET.get('cartids')
        # 接收的是字符串类型，把他转换为列表型
        cartids = eval(cartids)
        # print(cartids)
        # 获取购物车里的商品
        data = models.Cart.objects.filter(id__in=cartids)
        # 获取所有的一级城市数据
        citys = models.Citys.objects.filter(level=1)
        # 分配数据
        context = {'data':data,'citys':citys}
        # 加在模板
        return render(request,'home/orderconfirm.html',context)
    except:
        return HttpResponse('<script>history.back(-1);</script>')


# 前台商品列表
def  goodslist(request):
   
    # 接收id
    cid = request.GET.get('cid',43)
    # 通过对应的分类获取到对应的商品    
    ob = models.Cates.objects.get(id=cid)
    # 获取该类下的所有商品，除了下架商品 并且根据请求到了orderby来排序，ordernum按照升序，-ordernum降序，综合排序没有orderby，默认按照商品id来排序
    zob = ob.goods_set.all().exclude(status=2).order_by(request.GET.get('orderby','id'))

     # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类 参数1是获取的所有的数据对象，参数2是每页显示多少条
    paginator = Paginator(zob,12)

    # 获取当前页的数据
    p = request.GET.get('p',1)
    # 获取当前页的数据
    goodslist = paginator.page(p)
    context = {'data2':goodslist,'ob':ob}

    return render(request,'home/list.html',context)

# 前台商品信息
def  goodsinfo(request):

    # 获取商品id
    gid = request.GET.get('gid')
    # 获取商品对象通过id
    ob = models.Goods.objects.get(id=gid)
    # 分配数据
    context = {'data':ob}
    # 加载模板
    return render(request,'home/info.html',context)


def getcitys(request):
    # 获取请求的id参数
    upid = request.GET.get('id')

    # values()：一个对象构成一个字典，然后构成一个列表返回
    data = models.Citys.objects.filter(upid=upid).values()
    # print(data.length)
    # [object,object,object]
    # [{},{},{}]
    return JsonResponse(list(data),safe=False)


# 收货地址添加
def addressadd(request):
    try:
        # 接收请求的收货地址
        data = request.GET.dict()
        # print(data,type(data))
        # 从session中获取当前的用户对象，存入数据库的uid
        uid = request.session['VipUser']['uid']
        data['uid'] = models.Users.objects.get(id=uid)
        # 存入数据库
        ob = models.Address(**data)
        ob.save()

        return JsonResponse({'erroe':0,'msg':'添加成功！'})
    except:
        return JsonResponse({'error':1,'msg':'添加失败！'})

# 收货地址获取
def addressget(request):
    try:
        # 获取seesion的用户id
        uid = request.session['VipUser']['uid']
        # 获取当前用户的所有收货地址 values()构成一个列表返回
        data = models.Address.objects.filter(uid=uid).values()
        # 遍历这个用户从数据库获取出来的数据
        for i in data:
            # 给数据库省的编号获取对应的名称
            i['sheng'] = models.Citys.objects.get(id=i['sheng']).name
            # 给数据库市的编号获取对应的名称
            i['shi'] = models.Citys.objects.get(id=i['shi']).name
            # 给数据库县的编号获取对应的名称
            i['xian'] = models.Citys.objects.get(id=i['xian']).name

        # 返回数据
        return JsonResponse({'error':0,'data1':list(data)},safe=False)
    except:
        return JsonResponse({'error':1,'msg':'您还没有增加收货地址哦～～～'})


# 订单设为默认
def addressdefault(request):
    # 获取设为默认地址的地址id
    aid = int(request.GET.get('aid'))
    # print(aid,type(aid))
    # 将该地址的ischecked改为１
    ob = models.Address.objects.get(id=aid)
    ob.ischecked = 1
    ob.save()
     # 获取seesion的用户id
    uid = request.session['VipUser']['uid']
    # 获取当前用户的所有收货地址 values()构成一个列表返回
    data = models.Address.objects.filter(uid=uid)
    # 遍历这个用户从数据库获取出来的数据
    for i in data:
        if i.id != ob.id:
            i.ischecked = 0
            i.save()

    return JsonResponse({'error':0})


# 收货地址删除
def addressdel(request):
    try:
        # 获取删除的收货地址的id
        aid = int(request.GET.get('aid'))
        # 获取收货地址对象
        ob = models.Address.objects.get(id=aid)
        ob.delete()
        return JsonResponse({'error':0,'msg':'删除成功！'})
    except:
        return JsonResponse({'error':1,'msg':'删除失败！'})


# 收货地址编辑
def addressedit(request):
    try:
        # 获取编辑的收货地址的id
        aid = int(request.GET.get('aid'))
        # 获取收货地址对象
        ob = models.Address.objects.get(id=aid)
        # 获取省的名称
        sheng = models.Citys.objects.get(id=ob.sheng)
        # 获取市的名称
        shi = models.Citys.objects.get(id=ob.shi)
        # 获取县的名称
        xian = models.Citys.objects.get(id=ob.xian)
        # 将改收货信息存入字典
        data = {}
        data['id'] = ob.id
        data['shouhuoren'] = ob.shouhuoren
        data['shouhuophone'] = ob.shouhuophone
        data['sheng'] = sheng.name
        data['shi'] = shi.name
        data['xian'] = xian.name
        data['info'] = ob.info
        data['ischecked'] = ob.ischecked
        # print(data)
        # 返回数据
        return JsonResponse({'error':0,'data1':data})
    except:
        return JsonResponse({'error':1})


# 收货地址执行编辑保存
def addresseditsave(request):
    try:
        # 接收修改之后的收货信息
        addrs = request.GET.dict()
        # print(addrs)
        # 获取该收货对象
        ob = models.Address.objects.get(id=int(addrs['aid']))
        # 将修改后的值存入数据库
        ob.shouhuoren = addrs['shouhuoren']
        ob.shouhuophone = addrs['shouhuophone']
        ob.sheng = addrs['sheng']
        ob.shi = addrs['shi']
        ob.xian = addrs['xian']
        ob.info = addrs['info']
        ob.save()

        return JsonResponse({'error':0})
    except:
        return JsonResponse({'error':1})


# 订单创建
def ordercreate(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # print(data) 
    # {'wuliu': 'shentong', 'buytype': 'weixin', 'addressid': '13', 'cartids': '["1","2","3","4"]'}
    # 添加订单
    # 首先需要获取用户对象
    user = models.Users.objects.get(id=request.session['VipUser']['uid'])
    # 获取地址信息
    addr = models.Address.objects.get(id=data['addressid'])
    # 通过id获取对应的省市县
    sheng = models.Citys.objects.get(id=addr.sheng).name
    shi = models.Citys.objects.get(id=addr.shi).name
    xian = models.Citys.objects.get(id=addr.xian).name
    shouhuoaddress = sheng+shi+xian+addr.info

    # 计算订单总价
    totalprice = 0
    cart = models.Cart.objects.filter(id__in=eval(data['cartids']))
    # 遍历循环每一个购物车商品，计算购物车商品的总价
    for i in cart:
        totalprice += i.num*i.goodsid.price
    # 准备订单数据
    orderdata = {'uid':user,'shouhuoren':addr.shouhuoren,'shouhuophone':addr.shouhuophone,'shouhuoaddress':shouhuoaddress,'buytype':data['buytype'],'wuliu':data['wuliu'],'totalprice':totalprice}
    # print(orderdata)
    # 将创建的订单存入数据库
    ob = models.Order(**orderdata)
    ob.save()

    # 生成订单详情
    for i in cart:
        # 创建订单详情对象
        orderinfo = models.OrderInfo()
        # 添加属性
        orderinfo.orderid = ob
        orderinfo.goodsid = i.goodsid.id
        orderinfo.title = i.goodsid.title
        orderinfo.pic_url = i.goodsid.pic_url
        orderinfo.price = i.goodsid.price
        orderinfo.num = i.num
        # 将订单详情存入数据库
        orderinfo.save()
        # 将确认订单的商品删除
        i.delete()
    # 跳转支付页面
    return HttpResponse('<script>location.href="/order/buy/?orderid='+str(ob.id)+'"</script>')

# 订单支付页面
def orderbuy(request):
    # 获取订单号
    orderid = request.GET.get('orderid')
    # 获取对应的订单信息
    order = models.Order.objects.get(id=orderid)
    # print(order)
    # 分配数据
    context = {'data':order}
    # 加载模板
    return render(request,'home/myinfo/success.html',context)


# 我的订单信息管理
def myorderinfo(request):
    # 获取当前用户
    user = models.Users.objects.get(id=request.session['VipUser']['uid'])
    # 获取数据库里所有的没有删除的数据
    datas = user.order_set.filter().exclude(status=4)
    # 获取未支付的订单
    data0 = user.order_set.filter(status=0)
    # 获取已支付待发货的订单
    data1 = user.order_set.filter(status=1)
    # 获取已发货待收货的商品
    data2 = user.order_set.filter(status=2)
    # 获取已收货，待评价的商品
    data3 = user.order_set.filter(status=3)

    # 分配数据
    context = {'datas':datas,'data0':data0,'data1':data1,'data2':data2,'data3':data3}
    # 加载模板
    return render(request,'home/myinfo/order.html',context)

# 我的订单删除
def myorderdel(request):
    try:
        # 获取删除订单的oid
        oid = int(request.GET.get('oid'))
        # print(oid)
        # 获取对应的订单
        order = models.Order.objects.get(id=oid)
        order.status = 4
        order.save()
        return JsonResponse({'error':0,'msg':'删除成功！'})
    except:
        return JsonResponse({'error':1})


# 地址管理
def addressmanage(request):

    # 获取seesion的用户id
    uid = request.session['VipUser']['uid']
    # 获取当前用户的所有收货地址
    data = models.Address.objects.filter(uid=uid).values()
    # 遍历这个用户从数据库获取出来的数据
    for i in data:
        # 给数据库省的编号获取对应的名称
        i['sheng'] = models.Citys.objects.get(id=i['sheng']).name
        # 给数据库市的编号获取对应的名称
        i['shi'] = models.Citys.objects.get(id=i['shi']).name
        # 给数据库县的编号获取对应的名称
        i['xian'] = models.Citys.objects.get(id=i['xian']).name
    # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level=1)
    # print(data)
    # <QuerySet [{'id': 13, 'shouhuophone': '18083335735', 'ischecked': False, 'sheng': '河北省', 'uid_id': 767, 'info': '回龙观', 'shouhuoren': '李雪宾', 'shi': '唐山市', 'xian': '丰润区'}, {'id': 15, 'shouhuophone': '18083335735', 'ischecked': True, 'sheng': '天津市', 'uid_id': 767, 'info': '安顺市高铁西站', 'shouhuoren': '丁念念', 'shi': '河东区', 'xian': '东新街道'}]>

    context = {'data':data,'citys':citys}

    # 返回数据
    return render(request,'home/myinfo/address.html',context)



def uploads(myfile):
    import time
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()
    return "/static/pics/"+filename

# 个人信息管理
def personalinformation(request):
    # 获取登陆的用户
    user = models.Users.objects.get(id=request.session['VipUser']['uid'])
    if request.method == 'GET':
        
        # print(user)
        # 分配数据
        context = {'user':user}
        # 加载模板
        return render(request,'home/myinfo/information.html',context)
    elif request.method == 'POST':
        # 密码判断
        if request.POST.get('password'):
            # 如果修改了密码就执行下面的语句
            user.password = make_password(request.POST['password'],None,'pbkdf2_sha256')
        user.username = request.POST.get('username')
        user.email = request.POST.get('email')
        user.age = request.POST.get('age')
        user.sex = request.POST.get('sex')
        # 判断是否更新了头像
        myfile = request.FILES.get('pic_url')
        # print(myfile)
        if myfile:
        # #     # 如果修改了头像，就要上传新的头像，并判断是否删除以前的头像
        #     if user.pic_url != '/static/pics/users.jpg':
        #         # 删除原来上传的头像
                # os.remove(BASE_DIR+user.pic_url)

        #     # 将新上传的头像更新
            user.pic_url = uploads(myfile)
        user.save()
        
        return HttpResponse('<script>alert("更新成功！");location.href="'+reverse('home_personalinformation')+'"</script>')



# 购物车添加
def cartadd(request):
    # 通过gid和session获取对应的商品和对应的用户
    gid = request.GET.get('gid')
    uid = request.session['VipUser']['uid']
    goods = models.Goods.objects.get(id=gid)
    user = models.Users.objects.get(id=uid)
    # 获取加入购物车的对应数量
    num = request.GET.get('num')

    # 如果再添加相同的商品．就需要检查该商品是否已经在购物车，用户是否是同一个
    res = models.Cart.objects.filter(goodsid=goods).filter(uid=user)
    # print(res)

    # 如果该商品存在
    if res.count():
        # res[0].num += int(num)
        # res[0].save()
        for i in res:
            i.num += int(num)
            i.save()
    else:
        # 该购物车没有此商品和此用户
        ob = models.Cart(goodsid=goods,uid=user,num=num)
        ob.save()

    return JsonResponse({'error':0,'msg':'恭喜你，加入购物成功'})


# 我的购物车
def shopcart(request):
    # try:
    # 通过用户id获取对应购物车
    data = models.Cart.objects.filter(uid=request.session['VipUser']['uid'])
    # print(data)
    # if data:
    # 分配数据
    context = {'data':data}
    # 加载模板
    return render(request,'home/cart.html',context)
    # except:
    #     return HttpResponse('<script>alert("请先登录！");history.back(-1);</script>')

# 购物车商品数量修改
def shopcartedit(request):
    # 获取cartid num
    cartid = request.GET.get('cartid')
    num = request.GET.get('num')

    # 获取对应的购物车对象
    ob = models.Cart.objects.get(id=cartid)
    # 将修改后的数量存入购物车表
    ob.num = int(num)
    ob.save()

    # 计算对应的商品数目的总金额
    totalprice = ob.goodsid.price*ob.num
    # 保留金额的两位小数点
    res = '{:.2f}'.format(totalprice)
    return JsonResponse({'error':0,'msg':'数据修改成功！','totalprice':res})


# 购物车删除
def shopcartdel(request):
    try:
        # 获取购物车的商品id
        cateid = request.GET.get('cateid',0)
        # 获取购物车的商品对象
        ob = models.Cart.objects.get(id=cateid)
        # 删除改购物车商品
        ob.delete()
        return JsonResponse({'error':0,'msg':"删除成功!"})
    except:
        return JsonResponse({'error':1,'msg':'删除失败！'})

# 购物车全部删除
def shopcartdels(request):
    try:
        # 接收请求过来的购物车商品id
        arrs = request.GET.get('arrs')
        if arrs=='':
            return JsonResponse({'error':0,'msg':"您没有选择所要删除的商品,请选择!"})
        # 切割字符串
        arrs = arrs.split(',')
        # 删除最后一个空字符串
        arrs.pop()
        # print(arrs,type(arrs))  #['4', '5', '6', '7', '8'] 
        # 循环遍历每一个购物车商品id
        for i in arrs:
            ob = models.Cart.objects.get(id=int(i))
            # print(ob)
            # ob.delete()
        return JsonResponse({'error':0,'msg':"删除成功!"})
    except:
        return JsonResponse({'error':1,'msg':"删除失败!"})

# 用户登录
def login(request):
    # 获取登录页面的路径
    prevpath = request.GET.get('prevpath','/')
    # 获取登录页面所携带的参数,因为获得的结果是字符串，需要用eval转换成字典类型
    args = eval(request.GET.get('args','{}'))

    # 定义一个空的字符串
    paths = ''
    # 把获得的参数取出来
    for k,v in args.items():
        paths += '&'+k+'='+v
    prevurl = prevpath+'?'+paths

    if request.method == 'GET':
        return render(request,'home/login.html')
    else:
        try:
            # print(request.POST.dict())
            # 先传过来的手机号获取用户
            ob = models.Users.objects.get(phone=request.POST['phone'])
            # print(ob)
            # 对比密码
            res = check_password(request.POST['password'],ob.password)
            # print(res)
            if res:
                # 用户名和密码都正确
                # 在session中存入登录凭证
                request.session['VipUser'] = {'username':ob.username,'phone':ob.phone,'uid':ob.id,'pic_url':ob.pic_url}
                    # 跳转到首页
                return HttpResponse('<script>alert("登录成功");location.href="'+prevurl+'"</script>')
            else:
                # 密码错误
                pass
        except:
            pass
            # 用户名不存在

        return HttpResponse('<script>alert("用户名或密码错误");location.href="'+reverse('home_login')+'"</script>')


# 退出
def logout(request):
    del request.session['VipUser']
    return HttpResponse('<script>alert("退出登录！");location.href="/";</script>')


# 用户注册
def register(request):
    if request.method == 'GET':
        return render(request,'home/register.html')
    else:
        try:
            # 验证手机和验证码是否和session中一致
            # if request.POST['phone'] != request.session['msgcode']['phone'] or request.POST['code'] != request.session['msgcode']['code']:
            #     return HttpResponse('<script>alert("注册失败，验证码不正确！");location.href="'+reverse('home_register')+'"</script>')
            # 密码加密
            password  = make_password(request.POST['password'], None, 'pbkdf2_sha256')
            # 生成随机的用户名
            username = 'user'+str(request.POST['phone'])
            data = {'username':username,'phone':request.POST['phone'],'password':password}
            # 执行注册
            ob = models.Users(**data)
            ob.save()
            # 跳转登录页面
            return HttpResponse('<script>alert("注册成功,请登录~");location.href="'+reverse('home_login')+'"</script>')
        except:
            return HttpResponse('<script>alert("注册失败~~");location.href="'+reverse('home_register')+'"</script>')



# 验证手机号
def checkphone(request):
    # 接收手机号
    phone = request.GET.get('phone')
    # 到数据库查询
    num = models.Users.objects.filter(phone=phone).count()

    if num:
        return JsonResponse({'error':1,'msg':'手机号码已存在'})
    else:
        return JsonResponse({'error':0,'msg':'手机号码不存在'})




# 手机短信验证码发送

# def sendmsg(request):
#     #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
#     #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
#     #注意事项：
#     #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
#     #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
#     #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
#     # import urllib2
#     import urllib
#     import urllib.request
#     import json
#     import random
#     #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
#     account  = "C71483718" 
#     #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
#     password = "f0fedc6aa70b717065bd1c3638931c88"
#     # 接收注册页面提供的手机号
#     mobile = request.GET.get('phone')
#     # 随机验证码
#     code = str(random.randint(10000,99999))
#     # 把验证码存入session
#     request.session['msgcode'] = {'phone':mobile,'code':code}
#     text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
#     data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
#     # 发起请求
#     req = urllib.request.urlopen(
#         url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
#         data= urllib.parse.urlencode(data).encode('utf-8')
#     )
#     # 获取响应内容
#     content =req.read()
#     # 解析结果
#     res = json.loads(content.decode('utf-8'))
#     print(res)
#     return HttpResponse(res)
